/*
 * @Author: szx
 * @Date: 2023-04-17 13:50:33
 * @LastEditTime: 2023-04-17 16:39:35
 * @Description:
 * @FilePath: \learn\fullstackopen\part6\redux-anecdotes-main\src\components\AnecdoteList.jsx
 */
import { useSelector, useDispatch } from 'react-redux';
import { increaseAnecdoteVote } from '../reducers/anecdoteReducer';
import { setNotification } from '../reducers/notificationReducer';

const AnecdoteList = () => {
    const anecdotes = useSelector((state) => {
        if (state.filter === '') return state.anecdotes;
        else return state.anecdotes.filter((anecdote) => anecdote.content.includes(state.filter));
    });
    const dispatch = useDispatch();

    const vote = (id) => {
        dispatch(increaseAnecdoteVote(id));
        const anecdote = anecdotes.find((anecdote) => anecdote.id === id);
        dispatch(setNotification(`You Vote '${anecdote.content}'`, 3));
    };
    return (
        <>
            <h2>Anecdotes</h2>
            {anecdotes.map((anecdote) => (
                <div key={anecdote.id}>
                    <div>{anecdote.content}</div>
                    <div>
                        has {anecdote.votes}
                        <button onClick={() => vote(anecdote.id)}>vote</button>
                    </div>
                </div>
            ))}
        </>
    );
};
export default AnecdoteList;
